<?php
namespace app\model;

use think\Model;

class DeviceGroup extends Model
{
    // 设置数据表名
    protected $name = 'device_group';
    
    // 设置字段信息
    protected $schema = [
        'id'          => 'int',
        'name'        => 'string',
        'parent_id'   => 'int',
        'level'       => 'int',
        'path'        => 'string',
        'description' => 'string',
        'create_time' => 'datetime',
        'update_time' => 'datetime',
        'delete_time' => 'datetime',
    ];
    
    // 开启自动写入时间戳
    protected $autoWriteTimestamp = true;
    
    // 软删除
    use \think\model\concern\SoftDelete;
    protected $deleteTime = 'delete_time';
    
    // 关联设备
    public function devices()
    {
        return $this->hasMany(Device::class, 'group_id');
    }
    
    // 关联子分组
    public function children()
    {
        return $this->hasMany(DeviceGroup::class, 'parent_id');
    }
    
    // 关联父分组
    public function parent()
    {
        return $this->belongsTo(DeviceGroup::class, 'parent_id');
    }
    
    // 获取设备组完整路径
    public static function getFullPathName($id)
    {
        $names = [];
        $group = self::find($id);
        
        if (!$group) {
            return '';
        }
        
        // 按path字段包含的ID顺序获取所有父级分组
        $parentIds = $group->path ? explode('-', trim($group->path, '-')) : [];
        if (!empty($parentIds)) {
            $parents = self::where('id', 'in', $parentIds)->column('name', 'id');
            foreach ($parentIds as $pid) {
                if (isset($parents[$pid])) {
                    $names[] = $parents[$pid];
                }
            }
        }
        
        $names[] = $group->name;
        
        return implode(' / ', $names);
    }
    
    // 更新设备组路径信息
    public static function updateGroupPath($id)
    {
        $group = self::find($id);
        if (!$group) {
            return false;
        }
        
        // 如果是顶级分组
        if ($group->parent_id == 0) {
            $group->path = '';
            $group->level = 1;
        } else {
            // 获取父分组
            $parent = self::find($group->parent_id);
            if (!$parent) {
                return false;
            }
            
            $group->level = $parent->level + 1;
            $group->path = ($parent->path ? $parent->path : '') . '-' . $parent->id . '-';
        }
        
        $group->save();
        
        // 更新所有子分组
        $children = self::where('parent_id', $id)->select();
        foreach ($children as $child) {
            self::updateGroupPath($child->id);
        }
        
        return true;
    }
    
    // 搜索分组名称
    public function searchNameAttr($query, $value)
    {
        if (!empty($value)) {
            $query->where('name', 'like', '%' . $value . '%');
        }
    }
    
    // 搜索父级分组
    public function searchParentIdAttr($query, $value)
    {
        if (is_numeric($value)) {
            $query->where('parent_id', $value);
        }
    }
} 